<template>
  <div class="material-list-container">
    <div class="material-list-text">分区: {{ type }}</div>
    <el-upload
      v-if="role=='teacher'"
      ref="upload"
      action=""
      :auto-upload="false"
      :http-request="submitUpload"
      :limit="1"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button style="margin-left: 10px;" size="small" type="success" @click="()=>{this.$refs.upload.submit();}">上传到服务器</el-button>
    </el-upload>
    <div class="material-list-download-item" v-for="(item, index) in downloadList" :key="item.id">
      <a :href="host+'/material/download?id='+item.id" class="download-icon">
        <i class="el-icon-download"/>
      </a>
      <div v-if="role=='teacher'" class="download-icon" @click="deleteOneMaterial(item.id, index)">
        <i class="el-icon-delete"/>
      </div>
      <a :href="host+'/material/download?id='+item.id" class="download-filename">
        {{item.filename}}
      </a>
    </div>
  </div>
</template>

<script>
import {uploadMaterial, getMaterialByType, deleteMaterial} from '../../api'
import {CLASSID_KEY, HOST} from '../../constants'
import {ROLE_KEY} from '../../constants'

export default {
  name: 'MaterialList',
  computed: {
    role: function() {
      return (!!localStorage.getItem(ROLE_KEY)) ? "teacher" : "guest"
    }
  },
  data() {
    return {
      name: 'MaterialList',
      type: localStorage.getItem(CLASSID_KEY),
      downloadList: [],
      host: HOST
    }
  },
  methods: {
    submitUpload({file}) {
      let formData = new FormData();
      const type = this.type;
      formData.append("file", file);
      formData.append("type", type)
      uploadMaterial(formData).then(res => {
        this.$message.success("上传成功")
        this.$refs.upload.clearFiles();
      })
    },
    deleteOneMaterial(id, index) {
      this.downloadList.splice(index, 1);
      deleteMaterial({id}).then(res => {
        console.log(res)
        this.$message.success("删除成功")
      })
    }
  },
  mounted: function() {
    getMaterialByType({type: this.type}).then(res => {
      console.log(res)
      this.downloadList = res.data;
    })
  }
}
</script>

<style lang="scss" scoped>
.material-list {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
  &-download-item {
    display: flex;
    background-color: white;
    height: 50px;
    border: 1px solid gainsboro;
    border-radius: 5px;
    margin-top: 10px;
    align-items: center;
    padding: 0 15px;
  }
}
.download-icon {
  font-size: 24px;
  margin-right: 20px;
  cursor: pointer;
}
.download-filename {
  color: #20a0ff;
  position: relative;
  top: 2px;
}
</style>
